package com.totoro.controller.request;

import com.totoro.pojo.*;
import com.totoro.service.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TOTORO
 * @date 2021/6/30 20:19
 * 产品 | 购买 | 退款货的跳转控制器
 */
@Controller
public class ProductAndBuyRequestController {

    @Autowired
    ProductService productService;
    @Autowired
    AddressService addressService;
    @Autowired
    ShopService shopService;
    @Autowired
    CartService cartService;
    @Autowired
    EvaluationService evaluationService;
    @Autowired
    UserService userService;


    /** 仅用于保存用户上一次点击的商品详情，搜索详情 */
    private Integer pid = 0, skuId = 0, sid = 0;

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public Integer getSkuId() {
        return skuId;
    }

    public void setSkuId(Integer skuId) {
        this.skuId = skuId;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    /**
     * 跳转至商品详情页面
     * @return
     */
    @SneakyThrows
    @RequestMapping("/buy")
    public String goProductDetail(@RequestParam("pid") int pid, @RequestParam(value = "skuCode", required = false, defaultValue = "0") int skuCode,
                                  @RequestParam(value = "sid", required = false, defaultValue = "0") int sid, Model model, HttpSession session, HttpServletRequest request){
        // 查寻商品数据
        Product product  = productService.findProductById(pid);
        // 如果该商品以删除或不存在
        if(null == product || product.getIsLanunched() == 0){
            String configCode= URLEncoder.encode("该商品不存在或已被下架、删除","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=ALREADY_OFFSHELF_DELETE&errorMsg="+configCode;
        }
        // 如果传入的SkuId == 0 （int的默认值） 则寻找该商品最低的skuId
       skuCode = skuCode==0?productService.findMaxSkuIdByPid(pid):skuCode;
       this.setPid(pid);
       this.setSkuId(skuCode);
       // 查找该商品的店铺数据
       sid = sid==0?shopService.findShopIdByPid(pid):sid;
       this.setSid(sid);
       Shop shop = shopService.findShopBySid(sid);
       ProductSpecs productSpecs = productService.findAssignSkuByPidAndSkuId(skuCode);
       // 获得商品评论
       List<ProductComment> productComments = evaluationService.findProductAllEvaluationByPid(pid, 0, "date");
       model.addAttribute("pid", pid);
       model.addAttribute("product", product);
       model.addAttribute("productSku", productSpecs);
       model.addAttribute("shop", shop);
       model.addAttribute("productComments", productComments);
       // 追评数、图片评数
        int appendEvaLength = 0, imageEvaLength = 0;
        for (ProductComment productComment : productComments) {
            if(productComment.getMarketSrOrder().getIsAppendComment() == 1){
                appendEvaLength++;
            }
            if(productComment.getIsHaveImage() == 1){
                imageEvaLength++;
            }
        }
        model.addAttribute("appendEvaLength", appendEvaLength);
        model.addAttribute("imageEvaLength", imageEvaLength);

        User user = (User) session.getAttribute("user");

       // 判断用户是否收藏了该宝贝，是否登录，如果没登陆，那就显示没收藏状态
        boolean isCollect = false;
        if(null != user) {
            if (null != productService.checkUserCollectProduct(user.getUserId(), pid)){
                isCollect = true;
            }
        }
        model.addAttribute("isCollect", isCollect);

       // 添加用户足迹
       if(null!=user){
           MyHistory repeat = userService.repeatHistory(user.getUserId(),pid);
           if(null==repeat){
               MyHistory myHistory = new MyHistory();
               myHistory.setUid(user.getUserId());
               myHistory.setPid(pid);
               userService.addMyHistory(myHistory);
           }
       }
       // 获得用户id，进行判断识别，添加该类别的浏览次数
//        String ip = IpUtil.getIpAddress(request);
        int cid = productService.findCategoryIdByPid(pid);
        productService.updateProductClickCount(pid);
        productService.updateCategoryClickCount(cid);

        SuperEvaluationFind superEvaluationFind = new SuperEvaluationFind();
        superEvaluationFind.setSlid(1);
        int allEvaluation = evaluationService.findUserAllEvaluationBySlid(superEvaluationFind).size();
        // 计算卖家分，宝贝分，物流分 （总分除评价数）
        double sellerStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopSellerStar() / allEvaluation));
        double babyStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopBabyStar() / allEvaluation));
        double logisticsStar = Double.parseDouble(String.format("%.2f", (double)shop.getShopLogisticsStar() / allEvaluation));
        model.addAttribute("sellerStar", sellerStar);
        model.addAttribute("babyStar", babyStar);
        model.addAttribute("logisticsStar", logisticsStar);
        // 获得同行最高分
        Shop otherMaxShop = shopService.findOtherMaxScore(1);
        // 计算自己与同行的平均分差距
        // 获得同行最高的评论数
        int otherMaxProductComments = evaluationService.findUserAllEvaluationBySlid(new SuperEvaluationFind(otherMaxShop.getSlid())).size();
        double otherMaxSellerStar =  Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopSellerStar() / otherMaxProductComments));
        double otherMaxBabyStar = Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopBabyStar() / otherMaxProductComments));
        double otherMaxLogisticsStar = Double.parseDouble(String.format("%.2f", (double)otherMaxShop.getShopLogisticsStar() / otherMaxProductComments));
        model.addAttribute("gapSellerStar", Double.parseDouble(String.format("%.2f", (double)sellerStar - otherMaxSellerStar)));
        model.addAttribute("gapBabyStar", Double.parseDouble(String.format("%.2f", (double)babyStar - otherMaxBabyStar)));
        model.addAttribute("gapLogisticsStar", Double.parseDouble(String.format("%.2f", (double)logisticsStar - otherMaxLogisticsStar)));

        // 店铺左侧栏
        List<ShopCategory> allCategory = shopService.findAllShopCategory(shop.getId());
        // 键值对通过类别id拿分类
        Map<String, ShopCategory> map = new HashMap<>();
        for (ShopCategory shopCategory : allCategory) {
            map.put(shopCategory.getId()+"", shopCategory);
        }
        model.addAttribute("allCategory", map);
        // 销量收藏排行
        List<Product> dealDescProducts = shopService.findTermDescProduct(shop.getId(), "t2.deal_count desc");
        List<Product> collectDescProducts = shopService.findTermDescProduct(shop.getId(), "t2.collect_count desc");
        model.addAttribute("dealDescProducts", dealDescProducts);
        model.addAttribute("collectDescProducts", collectDescProducts);
        boolean isCollectShop = true;
        // 判断用户是否收藏了本次店铺
        if(null == user){
            isCollectShop = false;
        } else {
           CollectShop collectShop = shopService.checkUserCollectShop(user.getUserId(), sid);
           if(null == collectShop){
               isCollectShop = false;
           }
        }
        model.addAttribute("isCollectShop", isCollectShop);

        // 查询这个店铺的其他商品
        Integer[] integers = productService.getRandShopProduct(sid, pid, 12);
        List<Product> otherProducts = productService.recommendPidFind(integers);
        Collections.shuffle(otherProducts);
        model.addAttribute("otherProducts", otherProducts);

        // 获得本店铺好评商品
        List<Product> goodProducts = productService.findShopOtherProducts(sid, pid, 8);
        model.addAttribute("goodProducts", goodProducts);

        // 查询推荐商品
        // 推荐思路：首先查询最近一个月的随机几条用户足迹（浏览过的商品）做分割关键字查询，
        // 再按照销量最高的随机几条商品记录
        // 其次是以搜索最高的商品记录
        List<Product> myHistories = new ArrayList<>();
        if(null != user){
            myHistories = productService.findRecentRandHistoryProducts(user.getUserId());
            Collections.reverse(myHistories);
        }
        List<Product> sourceProducts = new ArrayList<>();
        for (Product myProduct : myHistories) {
            sourceProducts.add(myProduct);
        }
        List<Product> products1 = productService.findHotRandHistoryProducts();
        List<Product> products2 = productService.findKeywordAgoProducts();

        sourceProducts.addAll(products1);
        sourceProducts.addAll(products2);
        // 去重
        List<Product> finalProducts = sourceProducts.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(Product::getId))),
                ArrayList::new));
        if(finalProducts.size() > 12){
            finalProducts = finalProducts.subList(0,12);
        }

        // 混淆集合
        Collections.shuffle(finalProducts);
        model.addAttribute("recommendProducts", finalProducts);

       return "product_buy";
//        return "include/product/bottom_content";
    }


    /**
     * 跳轉至購物車頁面
     * @return
     */
    @RequestMapping("/cart")
    public String goCartPage(@RequestParam(value = "findType", required = false, defaultValue = "1") int findType,
                             HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        // 获取该用户映射过的购物车集合
        List<Cart> carts = cartService.test(user.getUserId(), findType);

        // 查询不带条件的，统计其他条件的数量
        List<Cart> notTermCarts = cartService.test(user.getUserId(), 1);
        // 购物车轻量级数据直接计算
        int allProductLength = 0;
        int priceReductionProductLength = 0;
        int stockAlarmProductLength = 0;
        for (Cart notTermCart : notTermCarts) {
            for (Shop shop : notTermCart.getShops()) {
                for (Product product : shop.getProducts()){
                    if(product.getNowPrice() < product.getBeforePrice() && product.getBeforePrice() != 0){
                        priceReductionProductLength++;
                    }
                    if(product.getProductSpecs().getProductStock() <= 10){
                        stockAlarmProductLength++;
                    }
                    allProductLength++;
                }
            }
        }
        model.addAttribute("carts", carts);
        model.addAttribute("allProductLength", allProductLength);
        model.addAttribute("priceReductionProductLength", priceReductionProductLength);
        model.addAttribute("stockAlarmProductLength", stockAlarmProductLength);
        return "include/buy/cart";
    }
}
